package com.wyg.blog.controller.user;

import com.wyg.blog.model.user.SysRoleUser;
import com.wyg.blog.model.user.User;
import com.wyg.blog.service.user.RoleService;
import com.wyg.blog.service.user.SysRoleUserService;
import com.wyg.blog.service.user.UserService;
import com.wyg.blog.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @description:
 * @author: WYG
 * @time: 2020/6/29 20:07
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    SysRoleUserService sysRoleUserService;

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @PostMapping("/register")
    @CrossOrigin
    public JsonResult<Integer> register(@RequestBody Map<String,String> userInfo){
        if(userService.selectUserNum(userInfo.get("username")) == 0){
            User user = new User();
            user.setId(0);
            user.setStatus(true);
            user.setUsername(userInfo.get("username"));
            user.setPassword(encoder.encode(userInfo.get("password")));
            Integer uid = userService.insertUser(user);

            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setId(0);
            sysRoleUser.setUid(uid);
            Integer rid = roleService.selectRoleByName(userInfo.get("roleName")).getId();
            sysRoleUser.setRid(rid);
            boolean res = sysRoleUserService.insertRoleUser(sysRoleUser);
            if(res){
                return new JsonResult<>(1,"200","注册成功!");
            } else {
                return new JsonResult<>(0,"601","角色信息添加失败失败");
            }
        } else {
            return new JsonResult<>(0,"602","该用户已存在");
        }

    }
}
